<?php
namespace broadcast\payment;

use Yansongda\Pay\Pay;
use Yansongda\Pay\Log;

//https://pay.yansongda.cn/docs/v2/wechat/pay.html
//微信支付
class WechatPay
{
    protected $config = [
        'appid' => '', // APP APPID
        'app_id' => '', // 公众号 APPID
        'miniapp_id' => '', // 小程序 APPID
        'mch_id' => '',
        'key' => '',
        'notify_url' => '',
        'cert_client' => '', // optional，退款等情况时用到
        'cert_key' => '',// optional，退款等情况时用到
        'log' => [ // optional
            'file' => '',
            'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
            'type' => 'single', // optional, 可选 daily.
            'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
        ],
        'http' => [ // optional
            'timeout' => 5.0,
            'connect_timeout' => 5.0,
            // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
        ],
        'mode' => 'dev', // optional, dev/hk;当为 `hk` 时，为香港 gateway。
    ];

    public function __construct ($info)
    {
        $this->config['appid']  = $info['appid'];
        $this->config['app_id'] = $info['app_id'];
        $this->config['miniapp_id'] = $info['miniapp_id'];
        $this->config['mch_id']  = $info['mch_id'];
        $this->config['key']    = $info['key'];
        $this->config['notify_url']  = $info['notify_url'];
        $this->config['cert_client']  = $info['cert_client'];
        $this->config['cert_key']  = $info['cert_key'];
        $this->config['log']['file'] = app()->getRuntimePath() . 'log/alipay.log';
    }


    public function pay($data)
    {
        $order = [
            'out_trade_no' => date('YmdHis').mt_rand(1000, 9999),
            'total_fee' => $data['money'], // **单位：分**
            'body' => '微信充值',
            // 'openid' => 'onkVf1FjWS5SBIixxxxxxx',
        ];

        $pay = Pay::wechat($this->config)->mp($order);

        // $pay->appId
        // $pay->timeStamp
        // $pay->nonceStr
        // $pay->package
        // $pay->signType
    }

    public function notify()
    {
        $pay = Pay::wechat($this->config);

        try{
            $data = $pay->verify(); // 是的，验签就这么简单！

            Log::debug('Wechat notify', $data->all());
        } catch (\Exception $e) {
            // $e->getMessage();
        }
        
        return $pay->success()->send();// laravel 框架中请直接 `return $pay->success()`
    }


}
